package com.homework.zk;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ZkDbConnect {

    public static void main(String[] args) throws InterruptedException {
        ZkDbConnect zkDbConnect = new ZkDbConnect();
        zkDbConnect.connectZk();
        zkDbConnect.getConnect();

    }

    ZkClient zkClient = null;
    Connection con = null;
    JDBCInfo jdbcInfo = new JDBCInfo("jdbc:mysql://centos7-3:3306/test?characterEncoding=utf-8&useSSL=false","root","12345678");

    //连接zk
    public void connectZk() throws InterruptedException {
        zkClient = new ZkClient("centos7-1,centos7-2");
        System.out.println("zkclient is ready");

        //自定义序列化
        zkClient.setZkSerializer(new ZkStrSerializer());



        //如果不存在该路径，则创建该路径,并将初始值输入zk
        if(!zkClient.exists("/jdbc")){
            zkClient.createPersistent("/jdbc",jdbcInfo.toString());
            //创建jdbc连接，对初始值jdbc数据进行连接
            getConnect();

        }else { //如果路径存在，则去路径下读取数据，根据路径下数据进行jdbc连接
            String s = zkClient.readData("/jdbc").toString();
            String[] split = s.split("_");
            //将切分后的数据传入jdbcinfo的参数中
            jdbcInfo.setUrl(split[0]);
            jdbcInfo.setName(split[1]);
            jdbcInfo.setPassword(split[2]);

            getConnect();
        }

        //注册数据监听器
        zkClient.subscribeDataChanges("/jdbc", new IZkDataListener() {
            public void handleDataChange(String path, Object data) throws Exception {
                //展示改变后的数据
                System.out.println(path + "数据已改变，新数据是："+data);

                //将数据转换为string并进行切分
                String s = data.toString();
                String[] split = s.split("_");
                //将切分后的数据传入jdbcinfo的参数中
                jdbcInfo.setUrl(split[0]);
                jdbcInfo.setName(split[1]);
                jdbcInfo.setPassword(split[2]);

                //再次进行jdbc连接
                getConnect();

            }

            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path+"数据已删除");
            }
        });
        Thread.sleep(Integer.MAX_VALUE);
    }

    //通过初始值进行jdbc连接
    public void getConnect(){
        try {
            con = DriverManager.getConnection(jdbcInfo.getUrl(), jdbcInfo.getName(), jdbcInfo.getPassword());
            System.out.println("数据库连接成功："+jdbcInfo.getUrl()+"，账号："+jdbcInfo.getName()+"，密码："+jdbcInfo.getPassword());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }



}
